<template>
  <u-container :hasSearch="false">
    <template #container>
      <u-form :schema="schema" :dataSource="form" ref="editForm" :slotCount="1">
        <template #index1>
          <a-form-item label="头像">
            <a-upload
              v-model:fileList="fileList"
              name="file"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :action="action"
              :before-upload="beforeUpload"
              @change="handleOnChangeToUploadFile"
            >
              <img
                v-if="avatorUrl"
                :src="avatorUrl"
                alt="avatar"
                class="avatar"
              />
              <div v-else>
                <!-- todo -->
                <loading-outlined v-if="loading" />
                <plus-outlined v-else />
                <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>
          </a-form-item>
        </template>
        <template #footer>
          <u-button
            type="primary"
            color="#28a745"
            @click="handleOnClickToSubmit"
          >
            提交
          </u-button>
          <u-button type="primary" @click="handleOnClickToBack">
            返回
          </u-button>
        </template>
      </u-form>
    </template>
  </u-container>
</template>
<script>
import UICLI from "components/ui-cli";
import UIContainer from "basicLayoutComponent/UIContainer";
import {
  set2Form,
  showMess,
  isTel,
  isEmail,
  hex_encode,
  hex_decode,
  showImg
} from "utils/Util";

import { Form, Upload } from "ant-design-vue";
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons-vue";

import Index from "./index";

import { getUserById, saveUser, updateUserById } from "@/access/api/user/index";
import { getRoleGroupList } from "@/access/api/role/index"

export default {
  name: "AdminUserEdit",
  components: {
    UButton: UICLI.UButton,
    UForm: UICLI.UForm,
    UContainer: UIContainer,
    AForm: Form,
    AFormItem: Form.Item,
    AUpload: Upload,
    LoadingOutlined,
    PlusOutlined,
  },
  data() {
    return {
      action: process.env.VUE_APP_ROOT_URL + "/api/file",
      schema: Index.schema,
      query: {
        id: -1,
        env: "add",
      },
      form: {
        id: 0,
        userNum: "",
        nickName: "",
        realName: "",
        avator: "",
        sex: 0,
        ruleGroupId: "",
        userStatus: 0,
        userDesc: "",
        email: "",
        tel: "",
        birthday: "",
        loginName: "",
        loginType: 1,
      },
      loading: false,
      fileList: [],
      avatorUrl: "",
    };
  },
  methods: {
    init() {
      this.initParams();
      this.initData();
      this.initListener();
      this.getUserById();
    },
    initParams() {
      this.query.id = this.$route.params.id;
      this.query.env = this.$route.params.env;
    },
    initListener() {
      this.schema.groups[0].fields[5].change = (date, dateStr) => this.handleOnChangeToGetDate(dateStr);
    },
    initData() {
      getRoleGroupList()
        .then(res => {
          if(res) {
            this.schema.groups[0].fields[1].sourceData = res;
          }
        });
    },
    handleOnChangeToGetDate(dateStr) {
      this.form.birthday = dateStr;
    },
    getUserById() {
      if (this.query.id != -1) {
        getUserById({
          id: this.query.id,
        }).then((res) => {
          if (res) {
            set2Form(this.form, res);
            if (res.avator) {
              this.avatorUrl = showImg(res.avator);
            }
            if (res.tel) {
              this.form.loginName = hex_decode(res.tel);
            }
            if (res.email) {
              this.form.loginName = hex_decode(res.email);
            }
          }
        });
      }
    },
    handleOnClickToBack() {
      this.$router.push("/list/admin/user");
    },
    handleOnClickToSubmit() {
      this.$refs.editForm.$refs.form
        .validate()
        .then(() => {
          if(isTel(this.form.loginName)) {
            this.form.tel = hex_encode(this.form.loginName)
            this.form.loginType = 1
          }
          
          if(isEmail(this.form.loginName)) {
            this.form.email = hex_encode(this.form.loginName)
            this.form.loginType = 2;
          }
          
          this.form.loginName = "";

          if (this.form.id) {
            // 修改
            updateUserById(this.form).then((res) => {
              if (res) {
                showMess("修改成功");
                this.handleOnClickToBack();
              }
            });
          } else {
            // 保存
            saveUser(this.form).then((res) => {
              if (res) {
                showMess("保存成功");
                this.handleOnClickToBack();
              }
            });
          }
        })
        .error((error) => {
          console.info(error);
        });
    },
    handleOnChangeToUploadFile(info) {
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        this.avatorUrl = showImg(info.file.response.data[0].uploadUrl);
        this.form.avator = info.file.response.data[0].uploadUrl;
        this.loading = false;
      }
      if (info.file.status === "error") {
        this.loading = false;
      }
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        showMess("Image must smaller than 1MB!", "error");
      }
      return isLt1M;
    },
  },
  created() {
    this.init();
  },
};
</script>

<style lang="less" scoped>
.avatar-uploader > .ant-upload,
.avatar-uploader .avatar {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>